<template>
  <el-dialog
    v-model="dialogVisible"
    title="本地文件列表"
    width="80%"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
  >
    <div class="local-file-list">
      <!-- 操作按钮 -->
      <div class="operate-buttons">
        <el-button
          type="primary"
          @click="handleBatchDeploy"
          :disabled="!selectedFiles.length"
          >批量入库</el-button
        >
        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="!selectedFiles.length"
          >批量删除</el-button
        >
      </div>

      <!-- 文件列表 -->
      <el-table
        :data="fileList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        max-height="500"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="filename" label="文件名" />
        <el-table-column prop="size" label="文件大小">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="modifiedTime" label="修改时间">
          <template #default="{ row }">
            {{ new Date(row.modifiedTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleDeploy(row)"
              >入库</el-button
            >
            <el-button size="small" type="danger" @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { deployLocalFiles, deleteLocalFile } from "@/api/modules/ueProject";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  fileList: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:visible", "refresh"]);

const dialogVisible = ref(props.visible);
const loading = ref(false);
const selectedFiles = ref([]);

// 监听visible属性变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
  }
);

// 监听对话框关闭
watch(
  () => dialogVisible.value,
  (newVal) => {
    emit("update:visible", newVal);
  }
);

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + " B";
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + " KB";
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + " MB";
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + " GB";
  }
};

// 表格选择事件
const handleSelectionChange = (selection) => {
  selectedFiles.value = selection.map((item) => item.filename);
  console.log(selectedFiles.value);
};

// 部署单个文件
const handleDeploy = async (row) => {
  try {
    loading.value = true;
    // TODO: 调用部署API
    ElMessage.success(`开始入库文件: ${row.filename}`);
    deployLocalFiles({ fileList: [row.filename] }).then((res) => {
      console.log(res);
    });
  } catch (error) {
    ElMessage.error("入库失败");
  } finally {
    loading.value = false;
  }
};

// 批量部署
const handleBatchDeploy = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning("请选择要入库的文件");
    return;
  }

  try {
    loading.value = true;
    // TODO: 调用批量部署API
    ElMessage.success(`开始批量入库 ${selectedFiles.value.length} 个文件`);
    deployLocalFiles({ fileList: selectedFiles.value }).then((res) => {
      console.log(res);
    });
  } catch (error) {
    ElMessage.error("批量入库失败");
  } finally {
    loading.value = false;
  }
};

// 删除单个文件
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文件 ${row.filename} 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    // TODO: 调用删除API
    ElMessage.success(`删除文件: ${row.filename}`);
    deleteLocalFile({ fileList: [row.filename] }).then((res) => {
      console.log(res);
    });
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning("请选择要删除的文件");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    // TODO: 调用批量删除API
    ElMessage.success(`开始批量删除 ${selectedFiles.value.length} 个文件`);
    deleteLocalFile({ fileList: selectedFiles.value }).then((res) => {
      console.log(res);
    });
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量删除失败");
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.local-file-list {
  padding: 0 20px;
}

.operate-buttons {
  margin-bottom: 20px;
}
</style>
